File System (fs) Node
Node.jsの標準モジュール modules
File System | Node.js v12.13.0 Documentation
The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.
code:file-system.js
const fs = require('fs');
非同期処理 asynchronousと同期処理がある
非同期処理 asynchronous
処理終了後
引数: エラーとファイルの内容
呼び出し:指定したコールバック関数 callback呼び出し
例
code:async.js
//callback(引き渡される関数)の第1引数err,第2引数でデータ受け取り
fs.readFile(path, options, function(err, data) {
// ...
});
同期処理
コールバック関数 callbackでなく、関数の返り値としてデータを取得
基本的に処理が止まったらまずい場合は非同期処理にすべき
code:sync.js
const data = fs.readFileSync(__dirname + '/test.txt', { encoding: 'utf8' });
ストリーム Stream
種類
Readable Stream
読み込み可能
Writable Stream
書き込み可能
Duplex Stream
読み書き両方が可能
Transform Stream
読み書きのタイミングでデータ加工が可能
カスタムストリーム